package org.jianfa.rpc.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.jianfa.learn.common.request.RpcRequest;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    private ApplicationContext applicationContext;

    public UserServiceHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //
        if (msg instanceof RpcRequest) {
            RpcRequest rpcRequest = (RpcRequest)msg;

            String className = rpcRequest.getClassName();
            Class clazz = Class.forName(className);
            Object object = applicationContext.getBean(clazz);

            String methodName = rpcRequest.getMethodName();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Method method = clazz.getDeclaredMethod(methodName, parameterTypes);

            Object[] parameters = rpcRequest.getParameters();

            Object result = method.invoke(object, parameters);

            ctx.writeAndFlush(result);
        }
    }
}